package cn.scw.common.separate;

import cn.scw.common.separate.model.MessageTemplateModel;
import cn.scw.common.utils.StringUtils;
import cn.scw.framework.redis.RedisCache;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class ServiceNumberService {

    private final static String APP_ID = "wxc7fe362657535bad";

    private final static String APP_SECRET = "53b5b3a841080a046d4c65d07104d3f3";

    private final static String ACCESS_TOKEN_URL = " https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";

    private final static String SEND_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";

    private final static String AUTHORIZATION_CODE = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";

    private final static String REDIS_ACCESS_TOKEN_1 = "REDIS_ACCESS_TOKEN_1";

    private final static String TEMPLATE_ID = "kyvwlGy-yaCNhb8uzWvcZBZh61DpYPK4HorBkbBQoAk";

    public String color = "#173177";

    @Resource
    private RedisCache redisCache;

    /**
     * 获取公众号access_token
     *
     * @return
     */
    private String getAccessToken() {
        try {
            String requestUrl = MessageFormat.format(ACCESS_TOKEN_URL, APP_ID, APP_SECRET);
            Connection connection = Jsoup.connect(requestUrl);
            String body = connection.ignoreContentType(true).ignoreHttpErrors(true).get().text();
            JSONObject object = JSONObject.parseObject(body);
            return object.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @return
     */
    public String getRedisAccessToken() {
        String accessToken = redisCache.getCacheObject(REDIS_ACCESS_TOKEN_1);
        if (StringUtils.isNotBlank(accessToken)) return accessToken;
        accessToken = getAccessToken();
        if (StringUtils.isNotBlank(accessToken)) {
            redisCache.setCacheObject(REDIS_ACCESS_TOKEN_1, accessToken, 7000, TimeUnit.SECONDS);
        }
        return accessToken;
    }

    /**
     * 发送模板消息
     *
     * @param touser        用户openID
     * @param templateModel 模板数据
     */
    public void sendTemplate(String touser, MessageTemplateModel templateModel) {
        try {
            String requestUrl = MessageFormat.format(SEND_TEMPLATE_URL, getRedisAccessToken());
            Connection connection = Jsoup.connect(requestUrl);
            Map<String, Object> dataMap = Maps.newHashMap();
            dataMap.put("touser", touser);
            dataMap.put("template_id", TEMPLATE_ID);
            dataMap.put("data", templateModel);
//            connection.data(dataMap);
            String body = connection.requestBody(JSONObject.toJSONString(dataMap)).ignoreHttpErrors(true).ignoreContentType(true).post().text();
            System.out.println("send template body：" + body);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 静默授权获取openID
     *
     * @param code
     * @return
     */
    public String getOpenId(String code) {
        try {
            Connection connection = Jsoup.connect(MessageFormat.format(AUTHORIZATION_CODE, APP_ID, APP_SECRET, code));
            String body = connection.ignoreContentType(true).ignoreHttpErrors(true).get().text();
            JSONObject object = JSONObject.parseObject(body);
            return object.getString("openid");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Value("${separate.oauth}")
    private String separateOauth;


    /**
     * 获取静默授权地址
     *
     * @return
     */
    public String getOauthUrl() {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=PRINTER_BASE#wechat_redirect";
        return MessageFormat.format(url, APP_ID, separateOauth);
    }
}
